import pandas as pd

class StandardScaler:
    def __init__(self):
        self.mean_ = None  # 每列的均值
        self.std_ = None   # 每列的标准差

    def fit(self, X):
        """计算每列的均值和标准差"""
        if isinstance(X, pd.DataFrame):  # 判断是否是 DataFrame
            self.mean_ = X.mean().to_dict()  # 保存为字典
            self.std_ = X.std().to_dict()    # 保存为字典
        else:
            n_samples, n_features = len(X), len(X[0])
            self.mean_ = [sum(row[i] for row in X) / n_samples for i in range(n_features)]
            self.std_ = [
                (sum((row[i] - self.mean_[i])**2 for row in X) / n_samples)**0.5 
                for i in range(n_features)
            ]

    def transform(self, X):
        """标准化数据"""
        if isinstance(X, pd.DataFrame):
            # DataFrame 标准化
            X_scaled = X.copy()  # 避免修改原始数据
            for col in X.columns:
                if self.std_[col] != 0:  # 防止标准差为零
                    X_scaled[col] = (X[col] - self.mean_[col]) / self.std_[col]
                else:
                    X_scaled[col] = 0
            return X_scaled
        else:
            # 列表标准化
            X_scaled = [
                [(row[i] - self.mean_[i]) / self.std_[i] if self.std_[i] != 0 else 0 for i in range(len(row))]
                for row in X
            ]
            return X_scaled

    def fit_transform(self, X):
        """结合 fit 和 transform"""
        self.fit(X)
        return self.transform(X)


if __name__ == "__main__":
    import pandas as pd
    x = [
        [1,2,3],
        [4,5,6],
        [7,8,9]
        ]
    X = pd.DataFrame([[1,2,3], [4,5,6], [7,8,9]])
    # print(X)
    scaler = StandardScaler()
    x_sclaer = scaler.fit_transform(X)
    print("均值为：", scaler.mean_)   # 实例属性
    print("方差为：", scaler.std_)
    print("标准化后为：", x_sclaer)
